package com.example.vote.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.vote.bean.*;
import com.example.vote.listener.ScoreContentLister;
import com.example.vote.listener.UserVoteLister;
import com.example.vote.listener.VoteListener;
import com.example.vote.mapper.TItemDao;
import com.example.vote.mapper.TItemVoteDao;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class TItemServiceImpl extends ServiceImpl<TItemDao, TItem> {

    @Autowired
    TVoteServiceImpl tVoteService;

    @Autowired
    UserVoteServiceImpl userVoteService;

    @Value("${qr_path}")
    String qrPath;
    @Autowired
    UserServiceImpl userService;

    @Autowired
    TItemVoteDao itemVoteDao;
    @Autowired
    ScoreContentService scoreContentService;
    @Autowired
    TItemVoteSubService itemVoteSubService;

    /**
     * 生成二维码
     *
     * @param itemId 二维码参数
     * @return
     * @throws WxErrorException
     */
    public String createQrCode(String itemId) throws WxErrorException {
        QrConfig config = new QrConfig(400, 400);
        return QrCodeUtil.generateAsBase64(qrPath + "?itemId=" + itemId, config, "png");
    }


    @Transactional
    public Result createVote(TItem item, MultipartFile[] files) throws IOException, WxErrorException {
        String phone = StpUtil.getLoginIdAsString();
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 生成二维码
        String qrCode = createQrCode(id);
        item.setId(id);
        item.setQrCode(qrCode);
        item.setCreateTime(LocalDateTime.now());
        item.setPhone(phone);
        boolean save = save(item);
        if (save) {
            VoteListener listener1 = new VoteListener(tVoteService, id);
            UserVoteLister listener2 = new UserVoteLister(userVoteService, id);
            ScoreContentLister listener3 = new ScoreContentLister(scoreContentService, id);
            // 投票人员
            EasyExcel.read(files[0].getInputStream(), TVote.class, listener1).sheet().doReadSync();
            // 限制人员投票
            List<UserVote> sync = EasyExcel.read(files[1].getInputStream(), UserVote.class, listener2).sheet().doReadSync();

            // 兼容老版本,只投票不评分
            if (item.getType().equals(2)) {
                // 投票选项
                EasyExcel.read(files[2].getInputStream(), ScoreContent.class, listener3).sheet().doReadSync();
            }

            for (UserVote userVote : sync) {
                User user = new User();
                user.setName(userVote.getName());
                user.setPhone(userVote.getPhone());
                User one = userService.lambdaQuery()
                        .eq(User::getPhone, userVote.getPhone())
                        .one();
                if (ObjectUtils.isEmpty(one)) {
                    try {
                        userService.save(user);
                    } catch (Exception e) {
                        log.error("创建用户失败,手机号不可重复{}", user.getPhone());
                    }
                }
            }
            return Result.success(null, "创建成功");
        }
        return Result.error("创建失败");
    }

    @Transactional
    public boolean deletedItem(String itemId) {
        // 删除投票项目
        removeById(itemId);

        // 删除限制人员
        LambdaQueryWrapper<UserVote> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserVote::getItemId, itemId);
        userVoteService.remove(wrapper);

        // 删除候选人员
        LambdaQueryWrapper<TVote> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(TVote::getItemId, itemId);
        tVoteService.remove(wrapper1);

        // 删除已打分人的人员
        LambdaQueryWrapper<TItemVote> wrapper2 = new LambdaQueryWrapper<TItemVote>().eq(TItemVote::getItemId, itemId);
        itemVoteDao.delete(wrapper2);

        // 删除副表
        LambdaQueryWrapper<TItemVoteSub> wrapper4 = new LambdaQueryWrapper<TItemVoteSub>().eq(TItemVoteSub::getItemId, itemId);
        itemVoteSubService.remove(wrapper4);

        // 删除评分项
        LambdaQueryWrapper<ScoreContent> wrapper3 = new LambdaQueryWrapper<ScoreContent>().eq(ScoreContent::getItemId, itemId);
        scoreContentService.remove(wrapper3);

        return true;
    }


    //    @Autowired
//    WxMaService wxMaService;

    //
//    @Value("${wechat.qrEnv}")
//    String env;

    //    public byte[] createQrCodeByte(String scene) throws WxErrorException {
//        byte[] bytes = wxMaService.getQrcodeService().createWxaCodeUnlimitBytes(scene,
//                "pages/vote/vote", false, env, 430, true, null, false);
//
//        return bytes;
//    }


//    @Transactional
//    public Result createVoteVo(VoteVo voteVo) throws WxErrorException {
//        String openId = SpringUtils.getOpenId();
//        if (!StringUtils.hasLength(openId)) {
//            // 未获取到openId
//            log.error("未获取到openId");
//            return Result.error("未获取到openId");
//        }
//        // 生成id
//        String id = UUID.randomUUID().toString().replace("-", "");
//        TItem item = voteVo.getItem();
//
//        // 生成二维码
//        byte[] qrCode = createQrCodeByte(id);
//
//        // 上传云空间
//        String fileId = uploadCloud(id, qrCode);
//        if (!StringUtils.hasLength(fileId)) {
//            log.error("上传云存储失败失败");
//            return Result.error("上传云存储失败失败");
//        }
//
//        item.setId(id);
//        item.setQrCode(fileId);
//        item.setCreateTime(LocalDateTime.now());
//        item.setCreateUser(openId);
//        boolean save = save(item);
//        if (!save) {
//            return Result.error("创建失败");
//        }
//        List<TVote> list = voteVo.getVotes();
//        for (TVote vote : list) {
//            vote.setItemId(id);
//        }
//        tVoteService.saveBatch(list);
//        return Result.success("创建成功", "success");
//    }


//    private String uploadCloud(String id, byte[] qrCode) throws WxErrorException {
//        WxCloudUploadFileResult cloudUploadFileResult = wxMaService.getCloudService().uploadFile("prod-5g9djfd0fa7fe87b", "qr/" + id + ".png");
//
//
//        //设置请求头
//        HttpHeaders requestHeaders = new HttpHeaders();
//        requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
//        //设置请求体
//        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
//        requestBody.add("key", "qr/" + id + ".png");
//        requestBody.add("Signature", cloudUploadFileResult.getAuthorization());
//        requestBody.add("x-cos-security-token", cloudUploadFileResult.getToken());
//        requestBody.add("x-cos-meta-fileid", cloudUploadFileResult.getCosFileId());
//        requestBody.add("file", qrCode);
//        HttpEntity requestEntity = new HttpEntity(requestBody, requestHeaders);
//
//
//        // 发送上传请求
//        ResponseEntity responseEntity = new RestTemplate().postForEntity(cloudUploadFileResult.getUrl(), requestEntity, HashMap.class);
//        if (responseEntity.getStatusCode().is2xxSuccessful()) {
//            //上传成功
//            return cloudUploadFileResult.getFileId();
//        }
//        //上传失败
//        return null;
//    }
}
